﻿using System;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
using Oxage.CNC.Models;

namespace Oxage.Common
{
	public class GCodePathDataConverter : IValueConverter
	{
		#region IValueConverter Members
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			//NOTE: Experimental, uses X and Y as linear movements, does not even check for G code number

			string gcode = value as string;
			var serializer = new GCodeSerializer();
			var model = serializer.Deserialize(gcode);

			var geometry = new PathGeometry();
			var figure = new PathFigure();
			figure.StartPoint = new Point(0, 0);
			foreach (var block in model.Blocks)
			{
				double x = 0, y = 0;
				foreach (var inline in block.Inlines.OfType<GCodeInline>().Where(i => !i.IsComment && i.Value != null))
				{
					switch (inline.Code)
					{
						case 'X':
							x = inline.Value.Value;
							break;

						case 'Y':
							y = inline.Value.Value;
							break;
					}
				}
				figure.Segments.Add(new LineSegment(new Point(x, y), true));
			}
			geometry.Figures.Add(figure);

			return geometry;
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			return null;
		}
		#endregion
	}
}
